

#include "source_manager.hpp"

#include "core/media_source.hpp"
#include "spdlog/spdlog.h"

using namespace mms;
SourceManager SourceManager::instance_;

bool SourceManager::add_source(const std::string &sourec_name, std::shared_ptr<MediaSource> source)
{
    std::lock_guard<std::mutex> lck(sources_mtx_);
    auto it = sources_.find(sourec_name);
    if(it != sources_.end()){
        return false;
    }
    sources_[sourec_name] = source;
    return true;
}

void SourceManager::add_source_if_not_exist(const std::string &source_name, std::shared_ptr<MediaSource> source)
{
    std::lock_guard<std::mutex> lck(sources_mtx_);
    auto it = sources_.find(source_name);
    if(it != sources_.end()){
        return;
    }
    sources_[source_name] = source;
    return;
}

bool SourceManager::remove_source(const std::string &source_name)
{
    std::lock_guard<std::mutex> lck(sources_mtx_);
    sources_.erase(source_name);
    return true;
}

std::shared_ptr<MediaSource> mms::SourceManager::get_source(const std::string &source_name)
{
   std::lock_guard<std::mutex> lck(sources_mtx_);
   auto it = sources_.find(source_name);
   if(it == sources_.end()){
        return nullptr;
   }
   return it->second;
}

std::unordered_map<std::string, std::shared_ptr<MediaSource>> SourceManager::get_sources()
{
    std::lock_guard<std::mutex> lck(sources_mtx_);
    return sources_;
}

void SourceManager::close()
{
    std::lock_guard<std::mutex> lck(sources_mtx_);
    for(auto it = sources_.begin(); it != sources_.end(); ++it){
        it->second->close();
    }
    sources_.clear();
}
